// 国际化配置
const translations = {
    zh: {
        keybindings: '键位绑定',
        movement: '窗口移动',
        move_left: '左移',
        move_down: '下移',
        move_up: '上移',
        move_right: '右移',
        resize: '窗口调整',
        resize_left: '向左调整',
        resize_down: '向下调整',
        resize_up: '向上调整',
        resize_right: '向右调整',
        options: '选项设置',
        enable_multiplexer: '启用终端复用器支持',
        ignore_special: '忽略特殊缓冲区',
        preview: '实时预览',
        generated_config: '生成的配置',
        copy: '复制',
        generate_share: '生成分享链接',
        copied: '已复制！',
        share_generated: '分享链接已生成'
    },
    en: {
        keybindings: 'Key Bindings',
        movement: 'Window Movement',
        move_left: 'Move Left',
        move_down: 'Move Down',
        move_up: 'Move Up',
        move_right: 'Move Right',
        resize: 'Window Resize',
        resize_left: 'Resize Left',
        resize_down: 'Resize Down',
        resize_up: 'Resize Up',
        resize_right: 'Resize Right',
        options: 'Options',
        enable_multiplexer: 'Enable Terminal Multiplexer Support',
        ignore_special: 'Ignore Special Buffers',
        preview: 'Live Preview',
        generated_config: 'Generated Configuration',
        copy: 'Copy',
        generate_share: 'Generate Share Link',
        copied: 'Copied!',
        share_generated: 'Share link generated'
    }
};

// 当前语言
let currentLang = 'zh';

// 键位配置
let keybindings = {
    move_left: { ctrl: true, key: 'h' },
    move_down: { ctrl: true, key: 'j' },
    move_up: { ctrl: true, key: 'k' },
    move_right: { ctrl: true, key: 'l' },
    resize_left: { alt: true, ctrl: true, key: 'h' },
    resize_down: { alt: true, ctrl: true, key: 'j' },
    resize_up: { alt: true, ctrl: true, key: 'k' },
    resize_right: { alt: true, ctrl: true, key: 'l' }
};

// 选项配置
let options = {
    multiplexer: true,
    ignored_buftypes: true
};

// 当前活动窗口
let activePane = 1;

// 初始化
document.addEventListener('DOMContentLoaded', function() {
    initializeApp();
});

function initializeApp() {
    setupLanguageSwitch();
    setupKeybindings();
    setupOptions();
    setupPreview();
    setupShare();
    updateGeneratedCode();
    updateLanguage();
}

// 语言切换
function setupLanguageSwitch() {
    const langZh = document.getElementById('lang-zh');
    const langEn = document.getElementById('lang-en');

    langZh.addEventListener('click', () => switchLanguage('zh'));
    langEn.addEventListener('click', () => switchLanguage('en'));
}

function switchLanguage(lang) {
    currentLang = lang;
    document.getElementById('lang-zh').classList.toggle('active', lang === 'zh');
    document.getElementById('lang-en').classList.toggle('active', lang === 'en');
    updateLanguage();
}

function updateLanguage() {
    const elements = document.querySelectorAll('[data-i18n]');
    elements.forEach(el => {
        const key = el.getAttribute('data-i18n');
        if (translations[currentLang][key]) {
            el.textContent = translations[currentLang][key];
        }
    });
}

// 键位绑定设置
function setupKeybindings() {
    const keyInputs = document.querySelectorAll('.key-input');
    keyInputs.forEach(input => {
        input.addEventListener('click', () => editKeybinding(input));
    });
}

function editKeybinding(element) {
    const direction = element.getAttribute('data-direction');
    const action = getActionFromDirection(direction);
    
    // 创建模态框让用户输入新键位
    const newBinding = prompt('请输入新的键位组合（例如：ctrl+h）:', getCurrentBinding(action));
    
    if (newBinding) {
        parseKeybinding(newBinding, action);
        updateKeybindingDisplay(action);
        updateGeneratedCode();
    }
}

function getActionFromDirection(direction) {
    const mapping = {
        'left': 'move_left',
        'down': 'move_down',
        'up': 'move_up',
        'right': 'move_right',
        'left-resize': 'resize_left',
        'down-resize': 'resize_down',
        'up-resize': 'resize_up',
        'right-resize': 'resize_right'
    };
    return mapping[direction];
}

function getCurrentBinding(action) {
    const binding = keybindings[action];
    let result = '';
    
    if (binding.alt) result += 'alt+';
    if (binding.ctrl) result += 'ctrl+';
    if (binding.shift) result += 'shift+';
    result += binding.key;
    
    return result;
}

function parseKeybinding(input, action) {
    const parts = input.toLowerCase().split('+');
    const key = parts.pop();
    
    keybindings[action] = {
        alt: parts.includes('alt'),
        ctrl: parts.includes('ctrl'),
        shift: parts.includes('shift'),
        key: key
    };
}

function updateKeybindingDisplay(action) {
    const direction = getDirectionFromAction(action);
    const element = document.querySelector(`[data-direction="${direction}"]`);
    
    if (element) {
        const binding = keybindings[action];
        let display = '';
        
        if (binding.ctrl) display += '<kbd>Ctrl</kbd> + ';
        if (binding.alt) display += '<kbd>Alt</kbd> + ';
        display += `<kbd>${binding.key.toUpperCase()}</kbd>`;
        
        element.innerHTML = display;
    }
}

function getDirectionFromAction(action) {
    const mapping = {
        'move_left': 'left',
        'move_down': 'down',
        'move_up': 'up',
        'move_right': 'right',
        'resize_left': 'left-resize',
        'resize_down': 'down-resize',
        'resize_up': 'up-resize',
        'resize_right': 'right-resize'
    };
    return mapping[action];
}

// 选项设置
function setupOptions() {
    const multiplexer = document.getElementById('multiplexer');
    const ignoredBuftypes = document.getElementById('ignored_buftypes');

    multiplexer.addEventListener('change', (e) => {
        options.multiplexer = e.target.checked;
        updateGeneratedCode();
    });

    ignoredBuftypes.addEventListener('change', (e) => {
        options.ignored_buftypes = e.target.checked;
        updateGeneratedCode();
    });
}

// 预览功能
function setupPreview() {
    const previewButtons = document.querySelectorAll('.preview-btn');
    previewButtons.forEach(btn => {
        btn.addEventListener('click', () => {
            const direction = btn.getAttribute('data-direction');
            moveActivePane(direction);
        });
    });
}

function moveActivePane(direction) {
    const panes = [1, 2, 3];
    let newActivePane = activePane;

    switch(direction) {
        case 'left':
            if (activePane === 2) newActivePane = 1;
            break;
        case 'right':
            if (activePane === 1) newActivePane = 2;
            break;
        case 'up':
            if (activePane === 3) newActivePane = 1;
            break;
        case 'down':
            if (activePane === 1 || activePane === 2) newActivePane = 3;
            break;
    }

    if (newActivePane !== activePane) {
        document.getElementById(`pane-${activePane}`).classList.remove('active');
        activePane = newActivePane;
        document.getElementById(`pane-${activePane}`).classList.add('active');
    }
}

// 生成配置代码
function updateGeneratedCode() {
    const code = generateLuaConfig();
    document.getElementById('generated-code').textContent = code;
}

function generateLuaConfig() {
    let config = `-- Smart-Splits 配置 - 由可视化配置器生成
-- Smart-Splits Configuration - Generated by Visual Configurator

local smart_splits = require('smart-splits')

-- 基本配置 / Basic Configuration
smart_splits.setup({
`;

    if (options.multiplexer) {
        config += `    -- 终端复用器支持 / Terminal Multiplexer Support
    multiplexer_integration = true,
`;
    }

    if (options.ignored_buftypes) {
        config += `    -- 忽略的缓冲区类型 / Ignored Buffer Types
    ignored_buftypes = { 'nofile', 'quickfix', 'prompt' },
`;
    }

    config += `})

-- 键位映射 / Key Mappings
local keymap = vim.keymap.set

-- 窗口移动 / Window Movement
`;

    // 生成移动键位
    for (const [action, binding] of Object.entries(keybindings)) {
        if (action.startsWith('move_')) {
            const direction = action.replace('move_', '');
            const keys = formatKeys(binding);
            config += `keymap('n', '${keys}', smart_splits.move_cursor_${direction}, { desc = 'Move to ${direction} window' })\n`;
        }
    }

    config += '\n-- 窗口调整 / Window Resize\n';

    // 生成调整键位
    for (const [action, binding] of Object.entries(keybindings)) {
        if (action.startsWith('resize_')) {
            const direction = action.replace('resize_', '');
            const keys = formatKeys(binding);
            config += `keymap('n', '${keys}', smart_splits.resize_${direction}, { desc = 'Resize window ${direction}' })\n`;
        }
    }

    return config;
}

function formatKeys(binding) {
    let result = '';
    if (binding.ctrl) result += '<C-';
    if (binding.alt) result += '<A-';
    if (binding.shift) result += '<S-';
    result += binding.key.toUpperCase();
    if (binding.ctrl || binding.alt || binding.shift) result += '>';
    return result;
}

// 分享功能
function setupShare() {
    const copyBtn = document.getElementById('copy-btn');
    const shareBtn = document.getElementById('share-btn');
    const copyLinkBtn = document.getElementById('copy-link-btn');

    copyBtn.addEventListener('click', copyToClipboard);
    shareBtn.addEventListener('click', generateShareLink);
    copyLinkBtn.addEventListener('click', copyShareLink);
}

function copyToClipboard() {
    const code = document.getElementById('generated-code').textContent;
    navigator.clipboard.writeText(code).then(() => {
        const btn = document.getElementById('copy-btn');
        const originalText = btn.innerHTML;
        btn.innerHTML = `<i class="fas fa-check"></i> ${translations[currentLang].copied}`;
        
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    });
}

function generateShareLink() {
    const config = {
        keybindings: keybindings,
        options: options,
        lang: currentLang
    };
    
    const encoded = btoa(JSON.stringify(config));
    const shareUrl = `${window.location.origin}${window.location.pathname}?config=${encoded}`;
    
    const shareLink = document.getElementById('share-link');
    const input = shareLink.querySelector('input');
    input.value = shareUrl;
    shareLink.style.display = 'flex';
    
    // 更新按钮文本
    const btn = document.getElementById('share-btn');
    const originalText = btn.innerHTML;
    btn.innerHTML = `<i class="fas fa-check"></i> ${translations[currentLang].share_generated}`;
    
    setTimeout(() => {
        btn.innerHTML = originalText;
    }, 2000);
}

function copyShareLink() {
    const input = document.getElementById('share-link').querySelector('input');
    input.select();
    document.execCommand('copy');
    
    const btn = document.getElementById('copy-link-btn');
    const originalHTML = btn.innerHTML;
    btn.innerHTML = '<i class="fas fa-check"></i>';
    
    setTimeout(() => {
        btn.innerHTML = originalHTML;
    }, 2000);
}

// 从URL加载配置
function loadConfigFromUrl() {
    const urlParams = new URLSearchParams(window.location.search);
    const configParam = urlParams.get('config');
    
    if (configParam) {
        try {
            const config = JSON.parse(atob(configParam));
            
            if (config.keybindings) {
                keybindings = { ...keybindings, ...config.keybindings };
                updateAllKeybindings();
            }
            
            if (config.options) {
                options = { ...options, ...config.options };
                document.getElementById('multiplexer').checked = options.multiplexer;
                document.getElementById('ignored_buftypes').checked = options.ignored_buftypes;
            }
            
            if (config.lang) {
                switchLanguage(config.lang);
            }
            
            updateGeneratedCode();
        } catch (e) {
            console.error('Failed to load config from URL:', e);
        }
    }
}

// 更新所有键位显示
function updateAllKeybindings() {
    for (const action of Object.keys(keybindings)) {
        updateKeybindingDisplay(action);
    }
}

// 页面加载时检查URL参数
window.addEventListener('load', loadConfigFromUrl);
